package com.hankol.material.limit;

import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;

import androidx.core.content.FileProvider;

import com.baselibrary.MessageBus;
import com.baselibrary.utils.EventBusUtils;
import com.baselibrary.bean.download.DownloadIO;
import com.baselibrary.bean.download.DownloadInfo;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.ObservableSource;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Function;
import io.reactivex.functions.Predicate;
import io.reactivex.schedulers.Schedulers;
import okhttp3.Call;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;


/**
 * Created by zs
 * Date：2018年 09月 12日
 * Time：13:56
 * —————————————————————————————————————
 * About: 下载管理（限制最大个数）
 * —————————————————————————————————————
 */
public class DownloadLimitManager {
    /**
     * 下载路径
     */
    public final static String FILE_PATH = Environment.getExternalStorageDirectory().getAbsolutePath() + "/素材库下载/";

    private static final AtomicReference<DownloadLimitManager> INSTANCE = new AtomicReference<>();
    private OkHttpClient mClient;
    private HashMap<String, Call> downCalls; // 用来存放各个下载的请求
    private List<DownloadInfo> downWait;           // 用来存放等待下载的请求
    public static int maxCount = 5;                // 同时下载的最大个数
    private final ThreadPoolExecutor mThreadPoolExecutor;
    private Handler mMainThread;

    public static DownloadLimitManager getInstance() {
        for (; ; ) {
            DownloadLimitManager current = INSTANCE.get();
            if (current != null) {
                return current;
            }
            current = new DownloadLimitManager();
            if (INSTANCE.compareAndSet(null, current)) {
                return current;
            }
        }
    }

    private DownloadLimitManager() {
        downCalls = new HashMap<>();
        mClient = new OkHttpClient.Builder().build();
        downWait = new ArrayList<>();
        mThreadPoolExecutor = new ThreadPoolExecutor(1, 3, 5,
                TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>(100));
    }

    public void execute(String url, OnFileSizeListener onFileSizeListener) {
        Runnable runnable = () -> {
            long contentLength = getContentLength(url);
            if (Looper.myLooper() != Looper.getMainLooper()) {
                if (mMainThread == null) mMainThread = new Handler(Looper.getMainLooper());
                mMainThread.post(() -> onFileSizeListener.onFileSize(contentLength));
            } else {
                onFileSizeListener.onFileSize(contentLength);
            }

        };
        mThreadPoolExecutor.execute(runnable);
    }

    /**
     * 查看是否在下载任务中
     *
     * @param url
     * @return
     */
    public boolean getDownloadUrl(String url) {
        if (url != null) {
            return downCalls.containsKey(url);
        }
        return false;
    }

    /**
     * 查看是否在等待任务中
     *
     * @param url
     * @return
     */
    public boolean getWaitUrl(String url) {
        for (DownloadInfo item : downWait) {
            if (item.getUrl().equals(url)) {
                return true;
            }
        }
        return false;
    }

    /**
     * 开始下载
     *
     * @param
     */
    public void download(DownloadInfo info) {
        EventBusUtils.sendNotify(MessageBus.msgid_start_download);
        Observable.just(info.getUrl())
                .filter(new Predicate<String>() { // 过滤 call的map中已经有了,就证明正在下载,则这次不下载
                    @Override
                    public boolean test(String s) {
                        boolean flag = downCalls.containsKey(s);
                        if (flag) {
                            // 如果已经在下载，查找下一个文件进行下载
                            downNext();
                            return false;
                        } else {
                            // 判断如果正在下载的个数达到最大限制，存到等下下载列表中
                            if (downCalls.size() >= maxCount) {
                                if (!getWaitUrl(s)) {
                                    downWait.add(info);
                                    DownloadInfo info = new DownloadInfo(s, DownloadInfo.DOWNLOAD_WAIT);
                                    EventBus.getDefault().post(info);
                                }
                                return false;
                            } else {
                                return true;
                            }
                        }
                    }
                })
                .flatMap(new Function<String, ObservableSource<?>>() { // 生成 DownloadInfo
                    @Override
                    public ObservableSource<?> apply(String s) {
                        return Observable.just(createDownInfo(s, info));
                    }
                })
                .map(new Function<Object, DownloadInfo>() { // 如果已经下载，重新命名
                    @Override
                    public DownloadInfo apply(Object o) {
                        return getRealFileName((DownloadInfo) o);
                    }
                })
                .flatMap(new Function<DownloadInfo, ObservableSource<DownloadInfo>>() { // 下载
                    @Override
                    public ObservableSource<DownloadInfo> apply(DownloadInfo downloadInfo) {
                        return Observable.create(new DownloadSubscribe(downloadInfo));
                    }
                })
                .observeOn(AndroidSchedulers.mainThread()) // 在主线程中回调
                .subscribeOn(Schedulers.io()) //  在子线程中执行
                .subscribe(new DownloadLimitObserver()); //  添加观察者，监听下载进度

    }

    /**
     * 下载等待下载中的第一条
     */
    public void downNext() {
        if (downCalls.size() < maxCount && downWait.size() > 0) {
            download(downWait.get(0));
            downWait.remove(0);
        }
    }

    /**
     * 下载取消或者暂停
     *
     * @param url
     */
    public void pauseDownload(String url) {
        Call call = downCalls.get(url);
        if (call != null) {
            call.cancel();//取消
        }
        downCalls.remove(url);
        downNext();
    }

    /**
     * 取消下载 删除本地文件
     *
     * @param info
     */
    public void cancelDownload(DownloadInfo info) {
        pauseDownload(info.getUrl());
        info.setProgress(0);
        info.setDownloadStatus(DownloadInfo.DOWNLOAD_CANCEL);
        EventBus.getDefault().post(info);
        deleteFile(info.getFileName());
    }

    /**
     * 创建DownInfo
     *
     * @param url 请求网址
     * @return DownInfo
     */
//    private DownloadInfo createDownInfo(String url) {
//        DownloadInfo downloadInfo = new DownloadInfo(url);
//        long contentLength = getContentLength(url);//获得文件大小
//        downloadInfo.setTotal(contentLength);
//        String fileName = url.substring(url.lastIndexOf("/"));
//        downloadInfo.setFileName(fileName);
//        return downloadInfo;
//    }

    /**
     * 创建DownInfo
     *
     * @param url 请求网址
     * @return DownInfo
     */
    public DownloadInfo createDownInfo(String url, DownloadInfo downloadInfo) {
//        DownloadInfo downloadInfo = new DownloadInfo(url);
        long contentLength = getContentLength(url);//获得文件大小
        downloadInfo.setTotal(contentLength);
//        String fileName = url.substring(url.lastIndexOf("/"));
//        downloadInfo.setFileName(info.getFileName());
        return downloadInfo;
    }

    /**
     * 如果文件已下载重新命名新文件名
     *
     * @param downloadInfo
     * @return
     */
    private DownloadInfo getRealFileName(DownloadInfo downloadInfo) {
        String fileName = downloadInfo.getFileName();
        long downloadLength = 0, contentLength = downloadInfo.getTotal();
        File path = new File(FILE_PATH);
        if (!path.exists()) {
            path.mkdir();
        }
        File file = null;
        if (path.isDirectory()) {
            file = new File(FILE_PATH, fileName);
        } else {
            if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
                file = new File(Environment.getExternalStorageDirectory() + "/素材库下载/" + fileName);
                if (!file.exists()) {
                    try {
                        file.createNewFile();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        if (file.exists()) {
            //找到了文件,代表已经下载过,则获取其长度
            downloadLength = file.length();
        }
        //之前下载过,需要重新来一个文件
//        int i = 1;
//        while (downloadLength >= contentLength) {
//            int dotIndex = fileName.lastIndexOf(".");
//            String fileNameOther;
//            if (dotIndex == -1) {
//                fileNameOther = fileName + "(" + i + ")";
//            } else {
//                fileNameOther = fileName.substring(0, dotIndex)
//                        + "(" + i + ")" + fileName.substring(dotIndex);
//            }
//            File newFile = new File(FILE_PATH, fileNameOther);
//            file = newFile;
//            downloadLength = newFile.length();
//            i++;
//        }
        //设置改变过的文件名/大小
        downloadInfo.setProgress(downloadLength);
        downloadInfo.setFileName(file.getName());
        downloadInfo.setPath(file.getPath());
        return downloadInfo;
    }

    private class DownloadSubscribe implements ObservableOnSubscribe<DownloadInfo> {
        private DownloadInfo downloadInfo;

        public DownloadSubscribe(DownloadInfo downloadInfo) {
            this.downloadInfo = downloadInfo;
        }

        @Override
        public void subscribe(ObservableEmitter<DownloadInfo> e) throws Exception {
            String url = downloadInfo.getUrl();
            long downloadLength = downloadInfo.getProgress();//已经下载好的长度
            long contentLength = downloadInfo.getTotal();//文件的总长度
            //初始进度信息
            e.onNext(downloadInfo);
            Request request = new Request.Builder()
                    //确定下载的范围,添加此头,则服务器就可以跳过已经下载好的部分
                    .addHeader("RANGE", "bytes=" + downloadLength + "-" + contentLength)
                    .url(url)
                    .build();
            Call call = mClient.newCall(request);
            downCalls.put(url, call);//把这个添加到call里,方便取消

            Response response = call.execute();
            File file = new File(FILE_PATH, downloadInfo.getFileName());

            if(downloadInfo.getType()==0){
                //图片下载
                InputStream is = null;
                RandomAccessFile fileOutputStream = null;
                try {
                    is = response.body().byteStream();
                    fileOutputStream = new RandomAccessFile(file, "rwd");
                    byte[] buffer = new byte[2048];//缓冲数组2kB
                    int len;
                    while ((len = is.read(buffer)) != -1) {
                        fileOutputStream.write(buffer, 0, len);
                        downloadLength += len;
                        downloadInfo.setProgress(downloadLength);
                        e.onNext(downloadInfo);
                    }
                    downCalls.remove(url);
                    downNext();
                } finally {
                    //关闭IO流
                    DownloadIO.closeAll(is, fileOutputStream);

                }
            }else {
                //视频、文件下载
                InputStream is = null;
                FileOutputStream fileOutputStream = null;
                try {
                    is = response.body().byteStream();
                    fileOutputStream = new FileOutputStream(file, true);
                    byte[] buffer = new byte[2048];//缓冲数组2kB
                    int len;
                    while ((len = is.read(buffer)) != -1) {
                        fileOutputStream.write(buffer, 0, len);
                        downloadLength += len;
                        downloadInfo.setProgress(downloadLength);
                        e.onNext(downloadInfo);
                    }
                    fileOutputStream.flush();
                    downCalls.remove(url);
                    downNext();
                } finally {
                    //关闭IO流
                    DownloadIO.closeAll(is, fileOutputStream);
                }
            }
            e.onComplete();//完成
        }
    }


    /**
     * 获取下载长度
     *
     * @param downloadUrl
     * @return
     */
    public long getContentLength(String downloadUrl) {
        Request request = new Request.Builder()
                .url(downloadUrl)
                .build();
        try {
            Response response = mClient.newCall(request).execute();
            if (response != null && response.isSuccessful()) {
                long contentLength = response.body().contentLength();
                response.close();
                return contentLength == 0 ? DownloadInfo.TOTAL_ERROR : contentLength;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return DownloadInfo.TOTAL_ERROR;
    }

    /**
     * 打开文件
     *
     * @param file
     */
    public static void openFile(Context context, File file) {

        try {
            Intent intent = new Intent();
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            //设置intent的Action属性
            intent.setAction(Intent.ACTION_VIEW);
            //获取文件file的MIME类型
            String type = getMIMEType(file);
            //设置intent的data和Type属性。android 7.0以上crash,改用provider
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                Uri fileUri = FileProvider.getUriForFile(context, context.getPackageName() + ".FileProvider", file);//android 7.0以上
                intent.setDataAndType(fileUri, type);
                grantUriPermission(context, fileUri, intent);
            } else {
                intent.setDataAndType(/*uri*/Uri.fromFile(file), type);
            }
            //跳转
            context.startActivity(intent);
        } catch (Exception e) {
            e.printStackTrace();
//            showAlert(context, "File corrupted, download again please.");
        }

    }

    /**
     * 根据文件后缀名获得对应的MIME类型。
     *
     * @param file
     */
    private static final String[][] MIME_MapTable = {
            //{后缀名， MIME类型}
            {".3gp", "video/3gpp"},
            {".apk", "application/vnd.android.package-archive"},
            {".asf", "video/x-ms-asf"},
            {".avi", "video/x-msvideo"},
            {".bin", "application/octet-stream"},
            {".bmp", "image/bmp"},
            {".c", "text/plain"},
            {".class", "application/octet-stream"},
            {".conf", "text/plain"},
            {".cpp", "text/plain"},
            {".doc", "application/msword"},
            {".docx", "application/vnd.openxmlformats-officedocument.wordprocessingml.document"},
            {".xls", "application/vnd.ms-excel"},
            {".xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"},
            {".exe", "application/octet-stream"},
            {".gif", "image/gif"},
            {".gtar", "application/x-gtar"},
            {".gz", "application/x-gzip"},
            {".h", "text/plain"},
            {".htm", "text/html"},
            {".html", "text/html"},
            {".jar", "application/java-archive"},
            {".java", "text/plain"},
            {".jpeg", "image/jpeg"},
            {".jpg", "image/jpeg"},
            {".js", "application/x-javascript"},
            {".log", "text/plain"},
            {".m3u", "audio/x-mpegurl"},
            {".m4a", "audio/mp4a-latm"},
            {".m4b", "audio/mp4a-latm"},
            {".m4p", "audio/mp4a-latm"},
            {".m4u", "video/vnd.mpegurl"},
            {".m4v", "video/x-m4v"},
            {".mov", "video/quicktime"},
            {".mp2", "audio/x-mpeg"},
            {".mp3", "audio/x-mpeg"},
            {".mp4", "video/mp4"},
            {".mpc", "application/vnd.mpohun.certificate"},
            {".mpe", "video/mpeg"},
            {".mpeg", "video/mpeg"},
            {".mpg", "video/mpeg"},
            {".mpg4", "video/mp4"},
            {".mpga", "audio/mpeg"},
            {".msg", "application/vnd.ms-outlook"},
            {".ogg", "audio/ogg"},
            {".pdf", "application/pdf"},
            {".png", "image/png"},
            {".pps", "application/vnd.ms-powerpoint"},
            {".ppt", "application/vnd.ms-powerpoint"},
            {".pptx", "application/vnd.openxmlformats-officedocument.presentationml.presentation"},
            {".prop", "text/plain"},
            {".rc", "text/plain"},
            {".rmvb", "audio/x-pn-realaudio"},
            {".rtf", "application/rtf"},
            {".sh", "text/plain"},
            {".tar", "application/x-tar"},
            {".tgz", "application/x-compressed"},
            {".txt", "text/plain"},
            {".wav", "audio/x-wav"},
            {".wma", "audio/x-ms-wma"},
            {".wmv", "audio/x-ms-wmv"},
            {".wps", "application/vnd.ms-works"},
            {".xml", "text/plain"},
            {".z", "application/x-compress"},
            {".zip", "application/x-zip-compressed"},
            {"", "*/*"}
    };

    public static String getMIMEType(File file) {

        String type = "*/*";
        String fName = file.getName();
        //获取后缀名前的分隔符"."在fName中的位置。
        int dotIndex = fName.lastIndexOf(".");
        if (dotIndex < 0) {
            return type;
        }
        /* 获取文件的后缀名 */
        String end = fName.substring(dotIndex, fName.length()).toLowerCase();
        if (end.equals("")) return type;
        //在MIME和文件类型的匹配表中找到对应的MIME类型。
        for (int i = 0; i < MIME_MapTable.length; i++) { //MIME_MapTable??在这里你一定有疑问，这个MIME_MapTable是什么？
            if (end.equals(MIME_MapTable[i][0]))
                type = MIME_MapTable[i][1];
        }
        return type;
    }

    private static void grantUriPermission(Context context, Uri fileUri, Intent intent) {
        List<ResolveInfo> resInfoList = context.getPackageManager().queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);
        for (ResolveInfo resolveInfo : resInfoList) {
            String packageName = resolveInfo.activityInfo.packageName;
            context.grantUriPermission(packageName, fileUri, Intent.FLAG_GRANT_WRITE_URI_PERMISSION | Intent.FLAG_GRANT_READ_URI_PERMISSION);
        }
    }

    /**
     * 删除文件
     *
     * @param fileName
     * @return
     */
    private static boolean deleteFile(String fileName) {
        boolean status;
        SecurityManager checker = new SecurityManager();
        File file = new File(FILE_PATH + fileName);
        if (file.exists()) {
            checker.checkDelete(file.toString());
            if (file.isFile()) {
                try {
                    file.delete();
                    status = true;
                } catch (SecurityException se) {
                    se.printStackTrace();
                    status = false;
                }
            } else
                status = false;
        } else
            status = false;
        return status;
    }

    public interface OnFileSizeListener {
        void onFileSize(long fileSize);
    }

}
